﻿Imports Ext.Net
Imports Ext.Net.MVC
Imports System.IO

Namespace DailyReport
    Public Class AssessController
        Inherits ControllerBase

        '
        ' GET: /Assess

        Function Index() As ActionResult
            Return View()
        End Function

        Function AssessList() As ActionResult
            ViewData("UserID") = CurrentUserID
            ViewData("CheckDate") = Now

            Return View()
        End Function

        Function AssessReport() As ActionResult
            Try
                Dim arm As New AssessReportModel
                Dim abtbnm As AssessBaseTypeByNameModel
                'Dim 
                Dim aim As AssessItemModel

                Dim mal As New List(Of Assess)
                Dim yal As New List(Of Assess)

                '先获创建新吉数据集
                Using re As New DailyReportEntitiesEX
                    Dim bts As List(Of AssessBaseType) = (From b In re.AssessBaseType Select b).ToList
                    Dim ofts As List(Of AssessFineType) = (From f In re.AssessFineType
                                                           Where f.isstatistics = 1
                                                           Order By f.sort Descending
                                                           Select f).ToList
                    Dim fts As List(Of AssessFineType)
                    Dim bti As String

                    '先将相同名喈BaseType塞去第一层
                    For Each bt In bts
                        '月
                        Dim tqm = (From a In arm.AssessBaseTypesByName
                                  Where a.AssessBasTypeName = bt.name
                                  Select a)
                        If tqm.Count > 0 Then
                            abtbnm = tqm.First
                            abtbnm.AssessBaseTypeIDs.Add(bt.id)
                        Else
                            abtbnm = New AssessBaseTypeByNameModel With {.AssessBasTypeName = bt.name}
                            abtbnm.AssessBaseTypeIDs.Add(bt.id)
                            abtbnm.AssessItems.Add(New AssessItemModel With {.assesstype = String.Concat(bt.name, "合计")})
                            arm.AssessBaseTypesByName.Add(abtbnm)
                        End If
                    Next

                    '然后循环每一个basetypeid 然后取出AssessItem
                    For Each abtbn In arm.AssessBaseTypesByName
                        '循环取出的FineType，然后再循环之，讲唔重复的数插入数据库 

                        For Each abti In abtbn.AssessBaseTypeIDs
                            fts = (From t In ofts
                                   Where t.basetype = abti
                                   Select t).ToList()
                            For Each ft In fts
                                Dim tq1 = (From a In abtbn.AssessItems
                                          Where a.assesstype = ft.name
                                          Select a)
                                If tq1.Count > 0 Then
                                Else
                                    aim = New AssessItemModel With {.assesstype = ft.name}
                                    abtbn.AssessItems.Add(aim)
                                End If
                            Next
                        Next
                    Next
                    arm.Total.assesstype = "房地产评估总计"

                    '插完吉表结构，准备开始填入真实喈数据
                    Dim StartDate As Date
                    '先查月
                    StartDate = New Date(Now.Year, Now.Month, 1)
                    mal = GetAssessOrgDate(StartDate)

                    StartDate = New Date(Now.Year, 1, 1)
                    yal = GetAssessOrgDate(StartDate)
                End Using

                ' 填数如
                Dim tal As List(Of Assess)
                For Each abtbn In arm.AssessBaseTypesByName
                    For Each ai In abtbn.AssessItems
                        Dim tq = (From al In mal
                              Where al.assesstype = ai.assesstype
                              Select al)
                        If tq.Count > 0 Then
                            tal = tq.ToList
                            For Each ta In tal
                                ai.assesscount = FormatInt(ai.assesscount, ta.assesscount)
                                ai.landarea = FormatDec(ai.landarea, ta.landarea)
                                ai.constructionarea = FormatDec(ai.constructionarea, ta.constructionarea)
                                ai.constructionprices = FormatDec(ai.constructionprices, ta.constructionprices)
                            Next
                        End If

                        abtbn.AssessItems(0).assesscount = FormatInt(abtbn.AssessItems(0).assesscount, ai.assesscount)
                        abtbn.AssessItems(0).landarea = FormatDec(abtbn.AssessItems(0).landarea, ai.landarea)
                        abtbn.AssessItems(0).constructionarea = FormatDec(abtbn.AssessItems(0).constructionarea, ai.constructionarea)
                        abtbn.AssessItems(0).constructionprices = FormatDec(abtbn.AssessItems(0).constructionprices, ai.constructionprices)
                    Next

                    arm.Total.assesscount = FormatInt(arm.Total.assesscount, abtbn.AssessItems(0).assesscount)
                    arm.Total.landarea = FormatDec(arm.Total.landarea, abtbn.AssessItems(0).landarea)
                    arm.Total.constructionarea = FormatDec(arm.Total.constructionarea, abtbn.AssessItems(0).constructionarea)
                    arm.Total.constructionprices = FormatDec(arm.Total.constructionprices, abtbn.AssessItems(0).constructionprices)
                Next

                For Each abtbn In arm.AssessBaseTypesByName
                    For Each ai In abtbn.AssessItems
                        Dim tq = (From al In yal
                              Where al.assesstype = ai.assesstype
                              Select al)
                        If tq.Count > 0 Then
                            tal = tq.ToList
                            For Each ta In tal
                                ai.yassesscount = FormatInt(ai.yassesscount, ta.assesscount)
                                ai.ylandarea = FormatDec(ai.ylandarea, ta.landarea)
                                ai.yconstructionarea = FormatDec(ai.yconstructionarea, ta.constructionarea)
                                ai.yconstructionprices = FormatDec(ai.yconstructionprices, ta.constructionprices)
                            Next
                        End If

                        abtbn.AssessItems(0).yassesscount = FormatInt(abtbn.AssessItems(0).yassesscount, ai.yassesscount)
                        abtbn.AssessItems(0).ylandarea = FormatDec(abtbn.AssessItems(0).ylandarea, ai.ylandarea)
                        abtbn.AssessItems(0).yconstructionarea = FormatDec(abtbn.AssessItems(0).yconstructionarea, ai.yconstructionarea)
                        abtbn.AssessItems(0).yconstructionprices = FormatDec(abtbn.AssessItems(0).yconstructionprices, ai.yconstructionprices)
                    Next

                    arm.Total.yassesscount = FormatInt(arm.Total.yassesscount, abtbn.AssessItems(0).yassesscount)
                    arm.Total.ylandarea = FormatDec(arm.Total.ylandarea, abtbn.AssessItems(0).ylandarea)
                    arm.Total.yconstructionarea = FormatDec(arm.Total.yconstructionarea, abtbn.AssessItems(0).yconstructionarea)
                    arm.Total.yconstructionprices = FormatDec(arm.Total.yconstructionprices, abtbn.AssessItems(0).yconstructionprices)
                Next
                Return View(arm)
            Catch ex As Exception
                Return View()
            End Try
        End Function

        Private Function GetAssessOrgDate(startDate As Date) As List(Of Assess)
            Try
                Dim aol As List(Of Assess)

                Using re As New DailyReportEntitiesEX
                    aol = (From c In re.Assess
                           Where c.createdate >= startDate And c.createdate <= Now Select c).ToList
                End Using
                Return aol
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Private Function FormatInt(org As String, add As String) As String
            Try
                Dim result = ""
                If Not String.IsNullOrEmpty(org) Or Not String.IsNullOrEmpty(add) Then
                    Dim t As Integer
                    Dim a As Integer
                    Integer.TryParse(org, t)
                    Integer.TryParse(add, a)
                    Dim out As Integer = t + a
                    If out > 0 Then
                        result = out.ToString
                    Else
                        result = ""
                    End If
                End If
                Return result
            Catch ex As Exception
                Return ""
            End Try
        End Function

        Private Function FormatDec(org As String, add As String) As String
            Try
                Dim result = ""
                If Not String.IsNullOrEmpty(org) Or Not String.IsNullOrEmpty(add) Then
                    Dim t As Decimal
                    Dim a As Decimal
                    Decimal.TryParse(org, t)
                    Decimal.TryParse(add, a)
                    Dim out As Decimal = t + a
                    If out > 0 Then
                        result = out.ToString
                    Else
                        result = ""
                    End If
                End If
                Return result
            Catch ex As Exception
                Return ""
            End Try
        End Function

        Public Function GetAssessStore(ByVal userid As String, ByVal createdate As Date, ByVal basetype As String) As AjaxStoreResult
            Try
                Dim startDate As Date
                Dim endDate As Date

                If Now.Day <= 27 Then
                    startDate = New Date(createdate.Year, createdate.Month - 1, 28)
                    endDate = Now
                Else
                    startDate = New Date(createdate.Year, Now.Month, 28)
                    endDate = Now
                End If

                Dim al As List(Of Assess)
                Using re As New DailyReportEntitiesEX
                    al = (From c In re.Assess
                          Where c.userid = userid And c.createdate >= startDate And c.createdate <= endDate And c.basetype = basetype
                          Select c).ToList
                End Using

                Return New AjaxStoreResult(al, al.Count)
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public Function SaveAssessWithConfirmation() As AjaxStoreResult
            Dim ajaxStoreResult As New AjaxStoreResult(StoreResponseFormat.Save)
            Try
                Dim dataHandler = New StoreDataHandler(HttpContext.Request("data"))
                Dim data As ChangeRecords(Of Assess) = dataHandler.ObjectData(Of Assess)()
                Dim confirmationList As ConfirmationList = dataHandler.BuildConfirmationList("assesstype")

                For Each dc In data.Created
                    Dim accessname = dc.assessname
                    If String.IsNullOrEmpty(accessname) Then
                        accessname = "空"
                    End If

                    Using re As New DailyReportEntitiesEX
                        Dim na As New Assess With {.id = System.Guid.NewGuid.ToString(),
                                                   .userid = CurrentUserID,
                                                   .basetype = dc.basetype,
                                                   .assesstype = dc.assesstype,
                                                   .assessname = accessname,
                                                   .assesscount = dc.assesscount,
                                                   .landarea = dc.landarea,
                                                   .landprices = dc.landprices,
                                                   .constructionarea = dc.constructionarea,
                                                   .constructionprices = dc.constructionprices,
                                                   .createdate = Now.ToString("yyyy-MM-dd")}
                        re.Assess.AddObject(na)
                        re.SaveChanges()
                    End Using
                Next

                For Each du In data.Updated
                    Using re As New DailyReportEntitiesEX
                        Dim oal = (From c In re.Assess
                                            Where c.id = du.id
                                            Select c)
                        Dim oa As Assess
                        If oal.Count > 0 Then
                            oa = oal.First
                            oa.assesstype = du.assesstype
                            oa.assesscount = du.assesscount
                            oa.assessname = du.assessname
                            oa.landarea = du.landarea
                            oa.landprices = du.landprices
                            oa.constructionarea = du.constructionarea
                            oa.constructionprices = du.constructionprices

                            re.SaveChanges()
                        End If
                    End Using
                Next

                For Each dd In data.Deleted
                    Using re As New DailyReportEntitiesEX
                        re.Assess.DeleteObject(dd)
                        'todo:删除有bug
                        re.SaveChanges()
                    End Using
                Next

                For Each c In confirmationList
                    confirmationList(c.Key).ConfirmRecord()
                Next

                ajaxStoreResult.SaveResponse.ConfirmationList = confirmationList
            Catch ex As Exception
                ajaxStoreResult.SaveResponse.Success = False
                ajaxStoreResult.SaveResponse.Message = ex.Message
            End Try

            Return ajaxStoreResult
        End Function

        Public Function GetAssessBaseTypeStore() As AjaxStoreResult
            Try
                Dim abtl As New List(Of AssessBaseTypeModel)
                Dim oabtl As List(Of AssessBaseType)
                Using re As New DailyReportEntitiesEX
                    oabtl = (From c In re.AssessBaseType
                            Select c).ToList
                End Using

                For Each bt In oabtl
                    abtl.Add(New AssessBaseTypeModel With {.ID = bt.id, .Name = String.Concat(bt.classify, "--", bt.name)})
                Next

                Return New AjaxStoreResult(abtl, abtl.Count)
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public Function GetAssessFineTypeStore(ByVal basetype As String) As AjaxStoreResult
            Try
                Dim aftl As New List(Of AssessFineType)
                Using re As New DailyReportEntitiesEX
                    aftl = (From c In re.AssessFineType
                            Where c.basetype = basetype
                            Select c).ToList
                End Using
                Return New AjaxStoreResult(aftl, aftl.Count)
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public Function ExportExcel(outputname As String) As ActionResult
            Try
                Dim exportTable As String = Request("exporttable")

                Response.Clear()
                Response.ContentType = "application/vnd.ms-excel"
                Response.ContentEncoding = System.Text.Encoding.UTF8
                Response.AddHeader("Content-Disposition", "attachment;filename=" + outputname + ".xls")
                Dim sw As New StringWriter
                sw.WriteLine(exportTable)
                Dim hw As New HtmlTextWriter(sw)
                Dim cr As New Control
                cr.RenderControl(hw)
                'Response.BinaryWrite(new byte()(,bb,bf))
                Response.Write(cr.ToString)

                Response.End()
                Return View()
            Catch ex As Exception
                Return View()
            End Try
        End Function
    End Class
End Namespace